package com.omni.dao.clause;

import java.sql.Types;
import org.apache.commons.lang3.StringUtils;
import com.omni.web.utils.DataUtil;

public class WhereClause {

	enum Conjunction {
		AND,
		OR,
	}

	private final StringBuffer clauses;

	private WhereClause() {
		clauses = new StringBuffer("(1=1)");
	}

	public static WhereClause create() {
		return new WhereClause();
	}

	private WhereClause combin(Conjunction conj, String clause, int valueType, Object value) {

		String conjstr = conj == Conjunction.AND ? " AND " : " OR ";

		if (StringUtils.isBlank(clause))
			return this;

		if (value == null) {
			clauses.append(conjstr + clause);
		} else {
			String sql = null;
			boolean isArray = value.getClass().isArray();
			if (Types.VARCHAR 		== valueType ||
			Types.NVARCHAR 	== valueType ||
			Types.NCHAR 		== valueType ||
			Types.CHAR 			== valueType ||
			Types.LONGVARCHAR 	== valueType ||
			Types.LONGNVARCHAR == valueType) {

			if (isArray)
				sql = DataUtil.buildArraySqlWithQuote(clause, "?", (Object[])value);
			else
				sql = DataUtil.buildSingleSqlWithQuote(clause, "?", (String)value);
			} else {

				if (isArray)
					sql = DataUtil.buildArraySql(clause, "?", (Object[])value);
				else
					sql = DataUtil.buildSingleSql(clause, "?", (String)value);
			}

			if (sql != null) {
				clauses.append(conjstr).append(sql);
			}
		}
		return this;
	}

	public WhereClause and(String sql) {

		return and(sql, -1, null);
	}

	public WhereClause and(String clause, int valueType, Object value) {

		return combin(Conjunction.AND, clause, valueType, value);
	}

	public WhereClause or(String sql) {

		return or(sql, -1, null);
	}

	public WhereClause or(String clause, int valueType, Object value) {

		return combin(Conjunction.OR, clause, valueType, value);
	}

	@Override
	public String toString() {

		return clauses.toString();
	}
}
